﻿using System;
using System.Reflection;
using System.Web;
using _5E.Utils.ReflectionHelper.Extension;

namespace _5E.Utils.WebHelper
{
    public abstract class AjaxManager
    {
        private HttpContext m_Context = null;
        protected HttpContext Context { get { return m_Context; } }

        protected abstract Type MappingType { get; }

        protected abstract MethodInfo MappingMethod { get; }

        public string GetResult(HttpContext context)
        {
            m_Context = context;
            string data = string.Empty;
            if (IsTerminate(ref data))
                return data;
            object result = MappingMethod.FastInvoke(
                CreateInstance(),
                GetMethodParameterValues());
            data = typeof(void) == MappingMethod.ReturnType ? AjaxHelper.ToData() : result.ToString();
            return data;
        }

        protected virtual bool IsTerminate(ref string result)
        {
            return false;
        }

        protected abstract object CreateInstance();

        protected object[] GetMethodParameterValues()
        {
            ParameterInfo[] parameters = MappingMethod.GetParameters();
            object[] parameterValues = new object[parameters.Length];
            for (Int32 i = 0; i < parameters.Length; i++)
            {
                ParameterInfo parameter = parameters[i];
                if (typeof(HttpPostedFile) == parameter.ParameterType)
                {
                    parameterValues[i] = Context.Request.Files[parameter.Name];
                }
                else
                {
                    string queryValue = Context.Request.Params[parameter.Name];
                    if (typeof(Guid) == parameter.ParameterType)
                    {
                        parameterValues[i] = string.IsNullOrEmpty(queryValue) ? Guid.Empty : new Guid(queryValue);
                    }
                    else
                    {
                        parameterValues[i] = string.IsNullOrEmpty(queryValue) ? null :
                            Convert.ChangeType(queryValue, parameter.ParameterType);
                    }
                }
            }
            return parameterValues;
        }
    }
}
